/**
 * @Title: RecordActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月19日 下午11:23:24
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.adapter.RecordAdapter;
import com.jason.fingerprint.beans.RecordBean;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.widget.PopWindow;
import com.jason.fingerprint.widget.PullToRefreshListView;

/**
 * @ClassName: RecordActivity
 * @Description: 档案查询
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月19日 下午11:23:24
 */
public class RecordActivity extends BaseActivity {

	private static final String TAG = "RecordActivity";
	public static final String RECORD_STATE = "record_state";
	public static final int QUERY_RECORD_STATE = 1000;
	public static final int ADD_RECORD_STATE = 1001;
	public static final int CHOOSE_RECORD_STATE = 1002;
	private static final int PAGE_COUNT = AppContext.PAGE_SIZE;
	public static final String UPDATE_RECORD_ACTION = "update_record_action";

	private PullToRefreshListView mListView;

	private AppContext mAppContext;
	private Handler mHandler;

	private RecordAdapter mRecordAdapter;
	private View mListViewFooter;
	private TextView mFooterMoreTextView;
	private ProgressBar mFooterProgressBar;
	private List<RecordBean> mRecordBeans = new ArrayList<RecordBean>();
	private int mDataCount;
	private int mPageIndex = 1;

	private PopWindow mInfoPopWindow;
	private PopWindow mSearchPopWindow;

	private LayoutInflater mLayoutInflater;
	public EditText mSearchEditText;
	@BindView(id = R.id.header_search,click = true)
	private Button mSearchButton;
	@BindView(id = R.id.header_back,click = true)
	private Button mBackButton;
	@BindView(id = R.id.header_title)
	private TextView mTitleTextView;
	@BindView(id = R.id.rl_record_title)
	private View mTitleLayout;
	
	@BindView(id = R.id.title_record_layout)
	private LinearLayout mTitleRecordLayout;
	@BindView(id = R.id.header_add,click = true)
	private Button mAddRecordLayout;
	
	private int mRecordState;
	
	private UpdateBroadcastReceiver mUpdateBroadcastReceiver;

	@Override
	public void setRootView() {
		setContentView(R.layout.activity_record);
	}
	
	/*
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initWidget()
	 */
	@Override
	protected void initWidget() {
		super.initWidget();
		init();
		initViewAndData();
		initListView();
		initListViewData();
		initPopViewInfo();
		initPopViewSearch();
		initBroadcastReceiver();
	}
	
	private void initBroadcastReceiver(){
		mUpdateBroadcastReceiver = new UpdateBroadcastReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(RecordActivity.UPDATE_RECORD_ACTION);
		registerReceiver(mUpdateBroadcastReceiver, filter);
	}
	
	private void init(){
		mTitleRecordLayout.setVisibility(View.VISIBLE);
		mTitleTextView.setText("档案查询");
		Intent intent = getIntent();
		if (intent != null) {
			//初始化指纹录入信息
			mRecordState = intent.getIntExtra(RECORD_STATE, ADD_RECORD_STATE);
			if (mRecordState == ADD_RECORD_STATE) {
				mTitleTextView.setText("指纹录入");
				mAddRecordLayout.setVisibility(View.VISIBLE);
			}else if (mRecordState == CHOOSE_RECORD_STATE) {
				mTitleTextView.setText("选择人员");
			}
		}
	}
	
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.header_search:
			showPopSearch();
			break;
		case R.id.header_back:
			KJActivityManager.create().finishActivity(RecordActivity.this);
			break;
		case R.id.header_add:
			//跳转到录入页面
			Intent intent = new Intent(RecordActivity.this,
					RecordAddOrUpdateActivity.class);
			intent.putExtra(RecordAddOrUpdateActivity.RECORD_STATE,
					RecordAddOrUpdateActivity.ADD_RECORD_STATE);
			startActivity(intent);
			break;

		default:
			break;
		}
	}
	
	private void initViewAndData(){
		mAppContext = (AppContext) getApplicationContext();
		mLayoutInflater = LayoutInflater.from(this);
		mInfoPopWindow = PopWindow.getInstance(this);
		mSearchPopWindow = PopWindow.getInstance(this);
	}
	
	private void showPopSearch(){
		//mSearchPopWindow.show(mTitleRelativeLayout, 0, 130, Gravity.TOP|Gravity.RIGHT);
		int[] location = new int[2];  
		mTitleLayout.getLocationOnScreen(location);
		//下方
		mSearchPopWindow.showAsDropDown(mTitleLayout);
		//上方
		//mSearchPopWindow.showAtLocation(mTitleRelativeLayout, Gravity.NO_GRAVITY, location[0], location[1]-mSearchPopWindow.getHeight());
		//左边
		//mSearchPopWindow.showAtLocation(mTitleRelativeLayout, Gravity.NO_GRAVITY, location[0]-mSearchPopWindow.getWidth(), location[1]);
		//右侧
		//mSearchPopWindow.showAtLocation(mTitleRelativeLayout, Gravity.NO_GRAVITY, location[0]+mTitleRelativeLayout.getWidth(), location[1]); 
	}

	private void initPopViewSearch() {
		View view = mLayoutInflater.inflate(R.layout.pop_record_search, null);
		mSearchEditText = (EditText) view.findViewById(R.id.et_pop_search);
		mSearchEditText.addTextChangedListener(mTextWatcher);
		mSearchPopWindow.setView(view, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
	}

	public TextWatcher mTextWatcher = new TextWatcher() {

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			// 搜索，更新数据
			loadListViewData(mPageIndex, mHandler,
					UIHelper.LISTVIEW_ACTION_SEARCH);
		}

	};
	
	private Button mCancleButton;

	// 初始化pop视图
	private void initPopViewInfo() {
		View view = mLayoutInflater.inflate(R.layout.pop_record_info, null);
		mCancleButton = (Button) view.findViewById(R.id.btn_cancle);
		mCancleButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mInfoPopWindow != null && mInfoPopWindow.isShowing()) {
					mInfoPopWindow.dismiss();
				}
			}
		});
		mInfoPopWindow.setView(view, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		mInfoPopWindow.setAnimationStyle(R.style.popup_down_up_animation);
	}

	// 初始化视图
	private void initListView() {
		mListView = (PullToRefreshListView) findViewById(R.id.record_listview);
		mRecordAdapter = new RecordAdapter(this, mRecordBeans);
		mListViewFooter = getLayoutInflater().inflate(R.layout.listview_footer,
				null);
		mFooterMoreTextView = (TextView) mListViewFooter
				.findViewById(R.id.listview_foot_more);
		mFooterProgressBar = (ProgressBar) mListViewFooter
				.findViewById(R.id.listview_foot_progress);
		mListView.addFooterView(mListViewFooter);
		mListView.setAdapter(mRecordAdapter);
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				RecordBean bean = (RecordBean) parent
						.getItemAtPosition(position);
				//showPopInfo(bean);
				Log.i(TAG, "setOnItemClickListener  " + bean);
				if (mRecordState == ADD_RECORD_STATE) {
					//跳转到添加修改页面
					Intent intent = new Intent(RecordActivity.this,
							RecordAddOrUpdateActivity.class);
					intent.putExtra(RecordAddOrUpdateActivity.RECORD_STATE,
							RecordAddOrUpdateActivity.UPDATE_RECORD_STATE);
					intent.putExtra("RecordBean", bean);
					startActivity(intent);
				}else if(mRecordState == CHOOSE_RECORD_STATE){
					Intent intent = new Intent();
					intent.putExtra("RecordBean", bean);
					setResult(RESULT_OK, intent);
					finish();
				}else{
					Intent intent = new Intent(RecordActivity.this, RecordInfoActivity.class);
					intent.putExtra("RecordBean", bean);
					startActivity(intent);
				}

			}
		});
		mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				mListView.onScrollStateChanged(view, scrollState);
				// 数据为空--不用继续下面代码了
				if (mRecordBeans.isEmpty())
					return;

				// 判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(mListViewFooter) == view
							.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}

				int lvDataState = StringUtils.toInt(mListView.getTag());
				if (scrollEnd && lvDataState == UIHelper.LISTVIEW_DATA_MORE) {
					mListView.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					mFooterMoreTextView.setText(R.string.load_ing);
					mFooterProgressBar.setVisibility(View.VISIBLE);
					// 当前pageIndex
					Log.i(TAG, "setOnScrollListener lvNewsSumData:"
							+ mDataCount);
					int pageIndex = mDataCount / PAGE_COUNT + 1;
					Log.i(TAG, "setOnScrollListener pageIndex:" + pageIndex);
					loadListViewData(pageIndex, mHandler,
							UIHelper.LISTVIEW_ACTION_SCROLL);
				}
			}

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				mListView.onScroll(view, firstVisibleItem, visibleItemCount,
						totalItemCount);
			}
		});

		mListView
				.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
					public void onRefresh() {
						loadListViewData(mPageIndex, mHandler,
								UIHelper.LISTVIEW_ACTION_REFRESH);
					}
				});
	}

	// 初始化ListView事件监听
	private void initListViewData() {
		mHandler = getHandler(mListView, mRecordAdapter, mFooterMoreTextView,
				mFooterProgressBar, PAGE_COUNT);
		if (mRecordBeans.isEmpty()) {
			loadListViewData(mPageIndex, mHandler,
					UIHelper.LISTVIEW_ACTION_INIT);
		}
	}
	
	// 更新数据
	private class UpdateBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			if (intent != null
					&& intent.getAction().equals(
							RecordActivity.UPDATE_RECORD_ACTION)) {
				loadListViewData(mPageIndex, mHandler,
						UIHelper.LISTVIEW_ACTION_REFRESH);
			}

		}
	};

	/****
	 * 获取listview的初始化Handler
	 * 
	 * @return
	 */
	private Handler getHandler(final PullToRefreshListView lv,
			final BaseAdapter adapter, final TextView more,
			final ProgressBar progress, final int pageSize) {
		return new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what >= 0) {
					// listview更新数据
					Log.i(TAG, "getHandler msg.what:" + msg.what + ",msg.arg1:"
							+ msg.arg1);
					handleListViewData(msg.what, msg.obj, msg.arg1);
					if (msg.what < pageSize) {
						lv.setTag(UIHelper.LISTVIEW_DATA_FULL);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_full);
					} else if (msg.what == pageSize) {
						lv.setTag(UIHelper.LISTVIEW_DATA_MORE);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_more);
					}

				} else if (msg.what == -1) {
					// 有异常--显示加载出错 & 弹出错误消息
					lv.setTag(UIHelper.LISTVIEW_DATA_MORE);
					more.setText(R.string.load_error);
				}
				if (adapter.getCount() == 0) {
					lv.setTag(UIHelper.LISTVIEW_DATA_EMPTY);
					more.setText(R.string.load_empty);
				}
				progress.setVisibility(ProgressBar.GONE);
				if (msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH) {
					lv.onRefreshComplete(getString(R.string.pull_to_refresh_update)
							+ new Date().toLocaleString());
					lv.setSelection(0);
				} else if (msg.arg1 == UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG) {
					lv.onRefreshComplete();
					lv.setSelection(0);
				}
			}
		};
	}

	// 更新数据
	private void handleListViewData(int what, Object obj, int actiontype) {
		Log.i(TAG, "handleLvData what:" + what + ",actiontype:" + actiontype);
		switch (actiontype) {
		case UIHelper.LISTVIEW_ACTION_INIT:
		case UIHelper.LISTVIEW_ACTION_REFRESH:
		case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
		case UIHelper.LISTVIEW_ACTION_SEARCH:
			List<RecordBean> nlist = (List<RecordBean>) obj;
			mDataCount = what;
			mRecordBeans.clear();// 先清除原有数据
			mRecordBeans.addAll(nlist);
			break;
		case UIHelper.LISTVIEW_ACTION_SCROLL:
			List<RecordBean> list = (List<RecordBean>) obj;
			mDataCount += what;
			mRecordBeans.addAll(list);
		}
	}

	// 加载数据
	private void loadListViewData(final int pageIndex, final Handler handler,
			final int action) {
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					List<RecordBean> list = loadData(pageIndex,action);
					if (list == null && list.size() == 0) {
						list = new ArrayList<RecordBean>();
					}
					msg.what = list.size();
					Log.i(TAG, "loadLvNewsData msg.what:" + msg.what);
					msg.obj = list;
				} catch (Exception e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				msg.arg1 = action;
				handler.sendMessage(msg);
			}
		}.start();
	}

	// 查询数据库
	private List<RecordBean> loadData(int index,int action) {
		String where = "";
		if (UIHelper.LISTVIEW_ACTION_SEARCH == action || UIHelper.LISTVIEW_ACTION_SCROLL == action) {
			Editable editable =  mSearchEditText != null ? mSearchEditText.getText() : null;
			String search = editable != null ? editable.toString() : "";
			if (!StringUtils.isEmpty(search)) {
				where = "where name like '%" + search + "%' " + "or telephone like '%" + search + "%'";
			}
		}else {
			if (mSearchEditText != null) {
				mSearchEditText.setText("");
			}
		}
		Log.i(TAG, "where:" + where);
		String sql = "SELECT * FROM table_record " + where + " limit " + PAGE_COUNT + " offset "
				+ PAGE_COUNT * (index - 1);
		Log.i(TAG, "sql:" + sql);
		return mAppContext.getKjdb().findDbModelListBySQL(
				RecordBean.class,sql);
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		Intent intent = new Intent();
		intent.putExtra("RecordBean", new RecordBean());
		setResult(RESULT_OK, intent);
		super.onBackPressed();
	}
	
	/* (non-Javadoc)
	 * @see org.kymjs.aframe.ui.activity.BaseActivity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mUpdateBroadcastReceiver != null) {
			unregisterReceiver(mUpdateBroadcastReceiver);
		}
	}

}
